classdef ClockSingleton < Singleton
   properties % Public Access
       current_time_in_msec = 0;
       tick_count = 0;
       objs_registered_for_ticks = [];
   end
   
   methods(Access = private)
       function obj = ClockSingleton()
           obj.current_time_in_msec = 0;
           obj.objs_registered_for_ticks = [];
       end
   end
   
   methods(Static)
      function obj = instance(should_reinit)
         persistent unique_instance;
         should_reinit = (nargin>0);
         if isempty(unique_instance) || (should_reinit==true)
            unique_instance = ClockSingleton();
         end
         obj = unique_instance;
      end
   end
   
   methods % Public Access
       function tick(obj)
           obj.forward_clock();
           
           utils = Utils.instance();
           utils.trace(sprintf('========= tick: %d. Time: %d (msec) ====== \n', obj.tick_count, obj.current_time_in_msec));
           
           for i=length(obj.objs_registered_for_ticks):-1:1
               curr_obj_to_notify = obj.objs_registered_for_ticks(i);
               curr_obj_to_notify.clock_tick_handler();
           end
       end
       
       function register_for_clock_ticks(this, obj)
           this.objs_registered_for_ticks = [this.objs_registered_for_ticks obj];
       end
       
       function forward_clock(obj)
           obj.current_time_in_msec = obj.current_time_in_msec + ParamsSingleton.instance().clock_tick_delta_in_msec;
           obj.tick_count = obj.tick_count + 1;
       end
   end
   
end